package com.myCinema.dao.impl;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.myCinema.dao.HibernateUtil;
import com.myCinema.dao.MovieDao;
import com.myCinema.entity.Movie;

public class MovieDaoImpl implements MovieDao {

	public List<Movie> getAll() {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			return sess.createQuery("from Movie").list(); 
		}finally{
			sess.close();
		}
	}

	public void add(Movie m) {
		Session sess = null;
		try{
			sess= HibernateUtil.openSession();
			Transaction tx = sess.beginTransaction();
			sess.save(m);
			tx.commit();
		}finally{
			sess.close();
		}
	}
	public Movie getMovieById(int id) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			Movie m = (Movie) sess.get(Movie.class, id);
			return m;
		}finally{
			sess.close();
		}
	}

	public static void main(String[] args) {
		new MovieDaoImpl().delete(21);
		
	}

	public void update(Movie m) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			Transaction tx = sess.beginTransaction();
			sess.update(m);
			tx.commit();
		}finally{
			sess.close();
		}
	}

	public void delete(int id) {
		Session sess = null;
		try {
			sess = HibernateUtil.openSession();
			Transaction tx = sess.beginTransaction();
			Movie m = (Movie)sess.get(Movie.class, id);
			sess.delete(m);
			tx.commit();
		} finally{
			sess.close();
		}
	}

	public List<Movie> paging(int cid, String title, int pageNum, int pageSize) {
		Session sess = null;
		try{
			Map<String, Object> m = new HashMap<String, Object>();
			sess = HibernateUtil.openSession();
			String hql = "from Movie m where 1=1";
			if(cid > 0){
				hql += "and m.category.id = :cid";
				m.put("cid", cid);
			}
			if(title != null && !title.isEmpty()){
				hql += "and m.title like :title";
				m.put("title", "%"+title+"%");
			}
			return sess.createQuery(hql)
					.setProperties(m)
					.setFirstResult((pageNum-1)*pageSize)
					.setMaxResults(pageSize).list();
		}finally{
			sess.close();
		}
	}
}	
